import { FilterOutlined, DownOutlined, RedoOutlined, DoubleRightOutlined } from '@ant-design/icons';
import { Button, Card, Form } from 'antd';
import { useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';
import ItemCard from './components/ItemCard';

// import type { FormProps, FormInstance } from 'antd';
import type { FilterCardType, FieldType, ValueType } from './types/index.type';

import './index.scss';

const FilterCard = (props: FilterCardType) => {
  const { className = 'mt-16', filterFormList } = props;
  const formContentRef = useRef<HTMLParagraphElement>(null);
  const [isExpand, setExpand] = useState(false);
  const [formDomHeight, setFormDomHeight] = useState<string>('48px');
  // const filterFormRef = useRef<FormInstance>(null);
  // 通过 Form.useForm 对表单数据域进行交互 相当于 useRef<FormInstance>(null) 进行控制
  const [filterFormRef] = Form.useForm();
  const [isShowExpandBtn, setShowExpandBtn] = useState(true);
  // * 立即查询
  const onFinish = () => {
    // const value = filterFormRef.getFieldsValue();
    const value = filterFormRef.getFieldsValue(true); // 过滤掉无值的字段
    const params = submitDataHandler(value);
    props.onFinish(params);
    // filterFormRef.submit(); // 与点击 submit 按钮效果相同，会走 onFinish 方法
  };
  // * 重置
  const onResetForm = () => {
    filterFormRef.resetFields();
    props.onReset();
  };
  // * 提交的数据处理
  const submitDataHandler = (value: ValueType) => {
    const newData = { ...value };
    // 检查openingTime是否存在且非null，然后映射日期格式
    if (value.openingTime && Array.isArray(value.openingTime)) {
      newData.openingTime = value.openingTime.map((item: Date) => dayjs(item).format('YYYY-MM-DD'));
    }
    // 检查birthdayMonth是否存在且非null，然后格式化日期
    if (value.birthdayMonth instanceof Date) {
      newData.birthdayMonth = dayjs(value.birthdayMonth).format('MM');
    }
    // 删除newData中所有值为undefined的属性
    Object.keys(newData).forEach(key => {
      if (newData[key] === undefined) {
        delete newData[key];
      }
    });
    // 返回新对象
    return newData;
  };
  // * 获取元素实际高度
  const getFormHeight = () => {
    const contentHeight = formContentRef.current?.offsetHeight ?? 0;
    return contentHeight;
  };
  // * 展开和收起
  const onExpandAndCollapse = () => {
    setExpand(isExpand => !isExpand); // 使用函数形式确保拿到最新状态
    const contentHeight = getFormHeight();
    const newHeight = isExpand ? '48px' : `${contentHeight}px`;
    setFormDomHeight(newHeight);
  };
  useEffect(() => {
    const contentHeight = getFormHeight();
    setShowExpandBtn(contentHeight > 48);
  }, []);
  return (
    <>
      <Card className={`${className} relative`}>
        {/*  */}
        <div className="flex justify-between">
          <div className="flex items-center">
            <FilterOutlined className="text-primary-color text-18" />
            <span className="text-color-title mx-4">请选择筛选条件</span>
            <DownOutlined
              className="cursor-pointer transition-all duration-200"
              style={{ transform: `rotate(${isExpand ? 0 : 180}deg)` }}
              onClick={onExpandAndCollapse}
            />
          </div>
          <div>
            <Button icon={<RedoOutlined rotate={-80} />} onClick={onResetForm}>
              重置
            </Button>
            <Button type="primary" className="bg-primary-color ml-8" onClick={onFinish}>
              点击查询
            </Button>
          </div>
        </div>
        {/*  */}
        <div className="overflow-hidden transition-all duration-200" style={{ height: formDomHeight }}>
          <div ref={formContentRef}>
            <Form
              form={filterFormRef}
              name="filterForm"
              layout="inline"
              labelAlign="right"
              labelCol={{ flex: '100px' }}
              wrapperCol={{ flex: 1 }}
            >
              {filterFormList.map((item, index) => {
                const { name, label, type, ...rest } = item;
                return (
                  <Form.Item<FieldType> label={label} name={name} key={index} className="mt-16 !mr-0 xl:w-[25%] 2xl:w-[20%]">
                    <ItemCard type={type} {...rest} />
                  </Form.Item>
                );
              })}
            </Form>
          </div>
        </div>
        {isShowExpandBtn && (
          <div className="expand_more" onClick={onExpandAndCollapse}>
            {isExpand ? '收起更多' : '展开更多'}
            <DoubleRightOutlined
              className="transition-all duration-300"
              style={{ transform: `rotate(${isExpand ? 90 : 270}deg)` }}
            />
          </div>
        )}
      </Card>
      {/* 为 expand_more div进行占位 */}
      {isShowExpandBtn && <div className="h-14"></div>}
    </>
  );
};

export default FilterCard;
